package com.wtwd.device.service.impl;

import com.alibaba.fastjson.JSONArray;
import com.wtwd.device.constant.RespCode;
import com.wtwd.device.dao.TempRecordMapper;
import com.wtwd.device.model.entity.TempInfo;
import com.wtwd.device.model.entity.TempRecord;
import com.wtwd.device.model.vo.RespEntity;
import com.wtwd.device.service.TempRecordService;
import com.wtwd.device.util.DateUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

/**
 * @author mjy
 * @date 2021/09/07
 * @description
 */
@Service
public class TempRecordServiceImpl implements TempRecordService {

    @Autowired
    private TempRecordMapper tempRecordMapper;

    @Override
    public RespEntity getDaysTempRecordList(Long deviceId, String startTime, String endTime) {
        List<TempRecord> tempRecords = tempRecordMapper.getDaysTempRecordList(deviceId, startTime, endTime);
        if (tempRecords != null && tempRecords.size() > 0) {
            tempRecords.forEach(tempRecord -> {
                tempRecord.setListTemp(JSONArray.parseArray(tempRecord.getTempInfo(), TempInfo.class));
            });
        }
        return new RespEntity(RespCode.SUCCESS, tempRecords);
    }

    @Override
    public RespEntity<List<TempRecord>> getMonthTempRecordList(Long deviceId, String month) {
        List<TempRecord> tempRecords = tempRecordMapper.getMonthTempRecordList(deviceId, month);
        if (tempRecords != null && tempRecords.size() > 0) {
            tempRecords.forEach(tempRecord -> {
                tempRecord.setListTemp(JSONArray.parseArray(tempRecord.getTempInfo(), TempInfo.class));
            });
        }
        return new RespEntity(RespCode.SUCCESS, tempRecords);
    }

    @Override
    public RespEntity addTempRecord(TempRecord tempRecord) {
        String time = DateUtils.format(tempRecord.getTime(), DateUtils.dateFormat5);
        TempRecord tempRecordOld = tempRecordMapper.getTempRecordByDeviceIdAndTime(tempRecord.getDeviceId(), time);
        if (tempRecordOld != null) {
            return new RespEntity(RespCode.TODAYS_DATA_ALREADY_EXIST);
        }
        tempRecord.setTempInfo(JSONArray.toJSONString(tempRecord.getListTemp()));
        tempRecord.setUploadTime(new Date().getTime());
        Integer rest = tempRecordMapper.addTempRecord(tempRecord);
        return new RespEntity(rest>0?RespCode.SUCCESS:RespCode.FAIL);
    }

    @Override
    public Integer clearTempRecordByDate(String date) {
        return tempRecordMapper.clearTempRecordByDate(date);
    }

    @Override
    public Integer deleteTempRecordByDeviceId(Long id) {
        return tempRecordMapper.deleteTempRecordByDeviceId(id);
    }
}
